/*
 * Copyright (c) 2024-2025.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.leafage.exploiter.service.impl;

import io.leafage.exploiter.domain.Script;
import io.leafage.exploiter.dto.ScriptDTO;
import io.leafage.exploiter.repository.ScriptRepository;
import io.leafage.exploiter.service.ScriptService;
import io.leafage.exploiter.vo.ScriptVO;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ScriptServiceImpl implements ScriptService {

    private final ScriptRepository scriptRepository;

    public ScriptServiceImpl(ScriptRepository scriptRepository) {
        this.scriptRepository = scriptRepository;
    }

    @Override
    public List<ScriptVO> retrieve(String name) {
        if (StringUtils.hasText(name)) {
            return scriptRepository.findAllByNameContaining(name).stream()
                    .map(script -> convertToVO(script, ScriptVO.class)).toList();
        }
        return scriptRepository.findAll().stream()
                .map(script -> convertToVO(script, ScriptVO.class)).toList();
    }

    @Override
    public ScriptVO fetch(Long id) {
        return scriptRepository.findById(id)
                .map(script -> convertToVO(script, ScriptVO.class)).orElse(null);
    }

    @Override
    public ScriptVO create(ScriptDTO dto) {
        Script script = convertToDomain(dto, Script.class);
        scriptRepository.save(script);
        return convertToVO(script, ScriptVO.class);
    }

    @Override
    public ScriptVO modify(Long id, ScriptDTO dto) {
        Assert.notNull(id, "id must not be null.");

        return scriptRepository.findById(id)
                .map(existing -> {
                    Script script = convert(dto, existing);
                    script = scriptRepository.save(script);
                    return convertToVO(script, ScriptVO.class);
                })
                .orElseThrow();
    }

    @Override
    public void remove(Long id) {
        Assert.notNull(id, "id must not be null.");

        scriptRepository.deleteById(id);
    }
}
